<template>
  <div>
    <el-table :data="healthCareList">
      <el-table-column prop="days" label="饲养天数">
        <template #default="{ row, $index }">
          <el-input v-if="editingIndex === $index" v-model="row.days" />
          <span v-else>{{ row.days }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="method" label="保健方式">
        <template #default="{ row, $index }">
          <el-input v-if="editingIndex === $index" v-model="row.method" />
          <span v-else>{{ row.method }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="way" label="保健方法">
        <template #default="{ row, $index }">
          <el-input v-if="editingIndex === $index" v-model="row.way" />
          <span v-else>{{ row.way }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-button v-if="editingIndex === $index" @click="saveEdit($index)">保存</el-button>
          <el-button v-if="editingIndex === $index" @click="cancelEdit">取消</el-button>
          <el-button v-else @click="startEdit($index)">修改</el-button>
          <el-button v-else @click="deleteItem($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="addRow">新增行</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElTable, ElTableColumn, ElInput, ElButton } from 'element-plus';

// 初始化保健信息列表
const healthCareList = ref([
  { id: 1, days: 35, method: '兔瘟单苗', way: '皮下注射' },
  { id: 2, days: 40, method: '巴二联苗', way: '皮下注射' }
]);
// 初始化编辑索引为 -1，表示没有正在编辑的行
const editingIndex = ref(-1);

// 新增行的方法
const addRow = () => {
  const newItem = { id: Date.now(), days: '', method: '', way: '' };
  healthCareList.value.push(newItem);
  editingIndex.value = healthCareList.value.length - 1;
};

// 开始编辑某一行的方法
const startEdit = (index) => {
  editingIndex.value = index;
};

// 保存编辑的方法
const saveEdit = (index) => {
  // 这里可以添加保存到后端的逻辑，例如使用 axios 发送请求
  console.log('保存数据:', healthCareList.value[index]);
  editingIndex.value = -1;
};

// 取消编辑的方法
const cancelEdit = () => {
  editingIndex.value = -1;
};

// 删除某一行的方法
const deleteItem = (index) => {
  healthCareList.value.splice(index, 1);
};
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>